#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
停靠窗口模块
提供查询历史、表结构、查询结果等停靠窗口
"""

import logging
from typing import Dict, List, Any, Optional
from datetime import datetime

from PySide6.QtCore import Qt, Signal, Slot
from PySide6.QtWidgets import (QDockWidget, QWidget, QVBoxLayout, QHBoxLayout,
                              QListWidget, QListWidgetItem, QMenu,
                              QLabel, QToolButton, QMessageBox, QTextEdit,
                              QTabWidget, QSplitter, QMainWindow)
from PySide6.QtGui import QFont, QIcon, QColor, QAction

from ui.widgets.table_schema import TableSchemaWidget
from ui.widgets.query_history import QueryHistoryWidget
from ui.results_view import ResultsView
from core.query_manager import get_query_manager, QueryResult
from config.settings import settings
from core.i18n import tr


# 初始化日志记录器
logger = logging.getLogger("dock_widgets")


class QueryHistoryDock(QDockWidget):
    """查询历史停靠窗口"""
    
    # 信号定义
    query_selected = Signal(str)  # 选中的查询文本
    
    def __init__(self, parent=None):
        """初始化查询历史停靠窗口
        
        Args:
            parent: 父窗口
        """
        super().__init__(tr("dock_query_history", "查询历史"), parent)
        self.setObjectName("QueryHistoryDock")  # 设置唯一对象名
        self._init_ui()
        
        # 允许所有停靠区域并设置特性
        self.setAllowedAreas(Qt.AllDockWidgetAreas)
        self.setFeatures(QDockWidget.DockWidgetMovable | 
                       QDockWidget.DockWidgetFloatable | 
                       QDockWidget.DockWidgetClosable)
        
    def _init_ui(self):
        """初始化UI"""
        # 创建查询历史组件
        self.query_history_widget = QueryHistoryWidget()
        
        # 设置为窗口部件
        self.setWidget(self.query_history_widget)
        
        # 连接信号
        self.query_history_widget.query_executed.connect(self.query_selected)
        
    def refresh(self):
        """刷新查询历史"""
        self.query_history_widget.refresh()


class TableSchemaDock(QDockWidget):
    """表结构停靠窗口"""
    
    # 信号定义
    query_generated = Signal(str)  # 生成的查询语句
    
    def __init__(self, parent=None):
        """初始化表结构停靠窗口
        
        Args:
            parent: 父窗口
        """
        super().__init__(tr("dock_table_schema", "表结构"), parent)
        self.setObjectName("TableSchemaDock")  # 设置唯一对象名
        self._init_ui()
        
        # 允许所有停靠区域并设置特性
        self.setAllowedAreas(Qt.AllDockWidgetAreas)
        self.setFeatures(QDockWidget.DockWidgetMovable | 
                       QDockWidget.DockWidgetFloatable | 
                       QDockWidget.DockWidgetClosable)
        
    def _init_ui(self):
        """初始化UI"""
        # 创建表结构组件
        self.table_schema_widget = TableSchemaWidget()
        
        # 设置为窗口部件
        self.setWidget(self.table_schema_widget)
        
        # 连接信号
        self.table_schema_widget.generate_query.connect(self.query_generated)
        
    def refresh(self):
        """刷新表结构"""
        self.table_schema_widget.refresh()


class ResultsDock(QDockWidget):
    """查询结果停靠窗口，显示数据、图表和查询信息"""
    
    def __init__(self, parent=None):
        """初始化查询结果停靠窗口
        
        Args:
            parent: 父窗口
        """
        super().__init__(tr("dock_results", "查询结果"), parent)
        self.setObjectName("ResultsDock")
        self._init_ui()
        
        # 允许所有停靠区域并设置特性
        self.setAllowedAreas(Qt.AllDockWidgetAreas)
        self.setFeatures(QDockWidget.DockWidgetMovable | 
                       QDockWidget.DockWidgetFloatable | 
                       QDockWidget.DockWidgetClosable)
        
        # 保存当前结果的元数据
        self.current_result_id = None
        self.current_result = None
        
        # 是否处于最大化状态
        self.is_maximized = False
        
    def _init_ui(self):
        """初始化UI"""
        # 主部件
        widget = QWidget()
        self.setWidget(widget)
        
        # 主布局
        layout = QVBoxLayout(widget)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 标题栏
        title_layout = QHBoxLayout()
        # title_label = QLabel("查询结果")
        # title_label.setStyleSheet("font-weight: bold;")
        
        # 刷新按钮
        refresh_button = QToolButton()
        refresh_button.setText(tr("button_refresh", "刷新"))
        refresh_button.setToolTip(tr("tooltip_refresh_history", "刷新查询结果"))
        refresh_button.clicked.connect(self._refresh_results)
        
        # 最大化按钮
        # maximize_button = QToolButton()
        # maximize_button.setText("最大化")
        # maximize_button.setToolTip("最大化结果视图")
        # maximize_button.clicked.connect(self._toggle_maximize)
        #
        # # title_layout.addWidget(title_label)
        # title_layout.addStretch()
        # title_layout.addWidget(refresh_button)
        # title_layout.addWidget(maximize_button)
        
        layout.addLayout(title_layout)
        
        # 创建结果视图
        self.results_view = ResultsView(self)
        
        layout.addWidget(self.results_view)
        
        # 存储最大化前的大小
        self.previous_size = None
        
    def display_result(self, result: QueryResult):
        """显示查询结果
        
        Args:
            result: 查询结果对象
        """
        if result is None:
            return
        
        # 保存当前结果
        self.current_result_id = result.query_id
        self.current_result = result
        
        # 调用结果视图的显示方法
        self.results_view.display_result(
            result.data,
            query_sql=result.query_text if hasattr(result, 'query_text') else None,
            execution_time=result.duration
        )
        
        # 更新标题
        self.set_title_with_stats(result)
        
    def set_title_with_stats(self, result: QueryResult):
        """根据结果设置窗口标题
        
        Args:
            result: 查询结果对象
        """
        if result and hasattr(result, 'row_count'):
            title = tr("results_title_format", "查询结果")
            self.setWindowTitle(title)
        else:
            self.setWindowTitle(tr("dock_results", "查询结果"))
    
    def _refresh_results(self):
        """刷新当前结果"""
        if self.current_result:
            self.display_result(self.current_result)
            
    def _toggle_maximize(self):
        """切换结果视图最大化状态"""
        main_window = self.parent()
        if not isinstance(main_window, QMainWindow):
            return
        
        if not self.is_maximized:
            # 保存当前状态
            self.previous_size = self.size()
            
            # 隐藏其他停靠窗口
            for dock in main_window.findChildren(QDockWidget):
                if dock != self and dock.isVisible():
                    dock.setVisible(False)
                    
            # 将自己设置为独占整个主窗口
            main_window.resizeDocks([self], [main_window.width()], Qt.Horizontal)
            main_window.resizeDocks([self], [main_window.height()], Qt.Vertical)
            
            # 更新按钮文本
            self.sender().setText("还原")
            self.sender().setToolTip("还原结果视图大小")
            
            self.is_maximized = True
        else:
            # 恢复其他停靠窗口
            for dock in main_window.findChildren(QDockWidget):
                if dock != self:
                    dock.setVisible(True)
                    
            # 还原之前的大小
            if self.previous_size:
                main_window.resizeDocks([self], [self.previous_size.width()], Qt.Horizontal)
                main_window.resizeDocks([self], [self.previous_size.height()], Qt.Vertical)
            
            # 更新按钮文本
            self.sender().setText("最大化")
            self.sender().setToolTip("最大化结果视图")
            
            self.is_maximized = False
    
    def cleanup(self):
        """清理资源"""
        if hasattr(self, 'results_view'):
            self.results_view.cleanup()
